package com.giscloud.commons.handler;

import com.giscloud.commons.enums.ResultEnum;
import com.giscloud.commons.exception.BusinessException;
import com.giscloud.commons.exception.TokenException;
import com.giscloud.commons.model.Result;
import com.giscloud.commons.utils.HttpUtil;
import com.giscloud.commons.utils.ResultUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author:giscloud
 * @Description:
 * @Date: 9:28 2019/9/12
 * @Modified By:
 */
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class,RuntimeException.class})
    @ResponseBody
    public Object handleException(Exception e, HttpServletRequest request, HandlerMethod handlerMethod) {
        log.error(e.getMessage(), e);
        if(HttpUtil.isAjax(handlerMethod) || HttpUtil.isAjax(request)) {
            if (e instanceof BusinessException) {
                return ResultUtil.error(e.getMessage());
            }else if (e instanceof TokenException) {
                return ResultUtil.error(-2,e.getMessage());
            }else if (e instanceof NoHandlerFoundException) {
                return ResultUtil.error(ResultEnum.NO_HANDLER_FOUND_ERROR);
            } else if (e instanceof IllegalArgumentException) {
                return ResultUtil.error(-4,e.getMessage());
            } else if (e instanceof IllegalStateException) {
                return ResultUtil.error(-5,e.getMessage());
            } else if (e instanceof BindException) {
                BindException ex = (BindException) e;
                List<ObjectError> allErrors = ex.getAllErrors();
                ObjectError error = allErrors.get(0);
                String defaultMessage = error.getDefaultMessage();
                return ResultUtil.error(-3,"参数绑定错误,"+defaultMessage);
            } else if (e instanceof HttpMessageNotReadableException) {
                return ResultUtil.error(-3,"参数类型不匹配，"+e.getMessage());
            }else if (e instanceof ValidationException) {
                return ResultUtil.error(-3,"参数校验错误，"+e.getMessage());
            } else if (e instanceof MethodArgumentNotValidException) {
                return ResultUtil.error(-3,"字段校验不通过，"+e.getMessage());
            }else if (e instanceof MissingServletRequestParameterException) {
                return ResultUtil.error(-3,"控制层参数绑定错误，"+e.getMessage());
            } else if (e instanceof HttpMediaTypeNotSupportedException) {
                return ResultUtil.error(-7,"请求类型不匹配，"+e.getMessage());
            } else if (e instanceof MaxUploadSizeExceededException) {
                return ResultUtil.error(-8,"请不要上传超过额定大小的文件");
            } else if (e instanceof HttpRequestMethodNotSupportedException) {
                return ResultUtil.error(-9,"不支持该类型的请求");
            } else if (e instanceof MethodArgumentNotValidException) {
                MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
                List<ObjectError> errors = ex.getBindingResult().getAllErrors();
                String message = errors.get(0).getDefaultMessage();
                return ResultUtil.error(-10,message);
            }else if(e instanceof SQLException){
                return ResultUtil.error(-11,"SQLException");
            } else if(StringUtils.isNotBlank(e.getMessage())){
                if(e.getMessage().contains("org.apache.ibatis")) {
                    return ResultUtil.error(-11,"SQLException");
                }else if(e.getMessage().contains("SQLException")) {
                    return ResultUtil.error(-12,"SQLException:"+e.getCause().getMessage());
                }else{
                    return ResultUtil.error(e.getMessage());
                }
            }else{
                log.error("全局拦截异常信息：{}",e);
                return ResultUtil.error(ResultEnum.UNKNOW_ERROR);
            }
        }else {
            ModelAndView modelAndView = new ModelAndView();
            //这里需要在templates文件夹下新建一个/error/500.html文件用作错误页面
            modelAndView.setViewName("/error/500");
            modelAndView.addObject("msg",e.getMessage());
            return modelAndView;
        }
    }
    /**
     * 捕捉404异常,这个方法只在配置
     * spring.mvc.throw-exception-if-no-handler-found=true来后起作用
     *
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handle(HttpServletRequest request, NoHandlerFoundException e) {
        log.error(e.getMessage(), e);
        return ResultUtil.error(404,"没有【"+request.getMethod()+"】"+request.getRequestURI()+"接口可以访问");
    }

}
